<template>
  <div class="scene">
    <!-- <div class="header">
      <span>创作场景：</span>
      <span>{{ detail.cat_name }}</span>
    </div> -->
    <!-- <div class="step-wrap">
      <a-steps :current="-1" size="small">
        <a-step title="拥有一个想法" description="挑选一个合适的模板" />
        <a-step title="补充一些介绍" description="输入一些简单的信息" />
        <a-step title="筛选心仪文案" description="编辑或润色好文案" />
        <a-step title="创作完成" description="发布" />
      </a-steps>
    </div> -->

    <div class="content-card" ref="contentPart">
      <div class="content-part content-split-vertical" style="width: 20%; display: flex; flex-direction: column">
        <div class="content-part-title">场景模板</div>
        <div class="cate-list beauty-scroller-bar" v-if="cateList.length > 0">
          <div class="cate-card" :class="currentCate.id == item.id ? 'cate-card-current' : ''"
            v-for="(item, index) of cateList" :key="index">
            <div class="cate-name">{{ item.cat_name }}</div>
            <template v-if="item.app_list && item.app_list.length > 0">
              <div v-for="(app, appIndex) of item.app_list" :key="appIndex" class="app-card"
                :class="currentApp.id == app.id ? 'app-card-current' : ''"
                :style="{ alignItems: app.info ? '' : 'center' }" @click="onAppClick(app)">
                <img :src="app.icon" alt="" class="app-icon" v-if="app.icon" />
                <div class="app-icon-block" v-else></div>
                <div class="app-right">
                  <div class="app-name">{{ app.name }}</div>
                  <div class="app-info" v-if="app.info">{{ app.info }}</div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>

      <div class="content-part content-card-part" style="width: 30%">
        <div class="content-part-title">开始创作</div>
        <div class="form-list beauty-scroller-bar">
          <template v-if="currentApp && currentApp.user_form">
            <a-form :wrapper-col="{ span: 24 }" layout="vertical" :model="formRef">
              <a-form-item v-for="(item, index) of currentApp.user_form" :key="index"
                v-bind="validateInfos['value' + index]">
                <template #label>
                  <div style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                      width: 100%;
                    ">
                    <div>{{ item.label }}</div>
                    <div v-if="item.patternIds && item.patternIds.length > 0">
                      <a-button type="link" style="padding: 0; margin: 0"
                        @click="showMaterialListPop(item, index)">智能推荐</a-button>
                    </div>
                  </div>
                </template>
                <template v-if="item.formType == 'input'">
                  <a-input v-model:value="formRef['value' + index]" :placeholder="item.placeholder || '请输入'" />
                </template>
                <template v-if="item.formType == 'textarea'">
                  <a-textarea v-model:value="formRef['value' + index]" :placeholder="item.placeholder || '请输入'"
                    :rows="4" />
                </template>
                <template v-if="
                  item.formType == 'select' &&
                  item.options &&
                  item.options.length > 0
                ">
                  <a-select v-model:value="formRef['value' + index]" :placeholder="item.placeholder || '请选择'" :options="item.options.map((item) => ({
                    label: item,
                    value: item,
                  }))
                    ">
                  </a-select>
                </template>
                <template v-if="item.formType == 'keywords'">
                  <div class="keywords-wrap">
                    <a-tag closable style="
                        border-radius: 6px;
                        white-space: pre-wrap;
                        word-break: break-all;
                        margin-bottom: 8px;
                      " v-for="(tagItem, tagIndex) of formRef['value' + index]" :key="tagIndex"
                      @close.prevent="removeKeywords(index, tagIndex)">{{ tagItem }}</a-tag>
                    <a-input v-model:value="item.newKeywords" style="width: 80px; height: 24px"
                      v-if="item.newKeywordsAdding" @pressEnter="(e) => addKeywords(e, item, index)"
                      @blur="addKeywords(null, item, index)" ref="newKeywordsInputRef" />
                    <div v-else class="add-keyword-button" @click="showAddKeywords(item)">
                      <PlusOutlined />
                      <span style="margin-left: 5px">添加</span>
                    </div>
                  </div>
                </template>
                <template v-if="
                  item.formType == 'multiSelect' &&
                  item.options &&
                  item.options.length > 0
                ">
                  <a-select v-model:value="formRef['value' + index]" :placeholder="item.placeholder || '请选择'"
                    mode="multiple" :options="item.options.map((item) => ({
                      label: item,
                      value: item,
                    }))
                      ">
                  </a-select>
                </template>
              </a-form-item>
            </a-form>
          </template>
        </div>

        <div class="form-submit-wrap">
          <a-button type="primary" style="
              width: 100%;
              height: 40px;
              border-radius: 20px;
              font-size: 16px;
            " :disabled="submitDisabled" @click="onSubmit">
            <template #icon>
              <ThunderboltOutlined />
            </template>
            智能创作文案
          </a-button>

          <a-tooltip>
            <template #title>该服务处于前沿探索阶段，您应当合法合规使用本服务，并承担由此产生的所有责任。我们对您的使用不做保证且不承担任何责任。</template>
            <div class="disclaimer-wrap" @click="disclaimerClick">
              <ExclamationCircleOutlined />
              免责声明
            </div>
          </a-tooltip>
        </div>
      </div>

      <div class="content-part content-card-part"
        style="width: 50%; background-color: #f5f5f5; border-left: 1px solid #f5f5f5;">
        <div class="flex justify-between align-center" style="background: #fff; padding: 0 5px">
          <a-tabs v-model:activeKey="activeKey" class="flex-1">
            <a-tab-pane v-for="item in tabList" :key="item.key">
              <template #tab>
                <span>
                  <PlusOutlined v-if="item.key == 2" />
                  <StarOutlined v-if="item.key == 1" />
                  <ClockCircleOutlined v-if="item.key == 0" />

                  {{ item.title }}
                </span>
              </template>
            </a-tab-pane>
          </a-tabs>
          <a-button type="link" @click="onStoreClick" v-if="activeKey == 2">保存</a-button>
        </div>
        <div class="history hide-scroller-bar" v-if="activeKey !== 2">
          <a-spin :spinning="historySpinning">
            <a-row style="
                margin: 10px;
                width: 100%;
                height: 100%;
                padding-right: 10px;
              " v-if="historyList.length">
              <a-col :span="24" v-for="history in historyList" :key="history.id" style="margin-bottom: 15px">
                <a-card style="border-radius: 5px">
                  <div class="title">
                    {{
                      activeKey == 1 ? history.collect_at : history.created_at
                    }}
                  </div>
                  <div class="introduce" v-if="!history.is_input" v-html="history.ai"></div>
                  <div class="pt-10 pb-10" v-else>
                    <scene-editor v-model:content="history.ai" placeholder="在左侧指令区输入相关信息" editorBgColor="#f5f5f5"
                      @change="() => aiTxtChange(history)" />
                  </div>
                  <div class="">
                    <a-space :size="20">
                      <!--  -->
                      <a-button :type="history.is_collect == 1 && item.key == 'collect'
                        ? 'primary'
                        : undefined
                        " shape="round" size="small" v-for="item in history.operateList" :key="item.key"
                        @click="btnClick(item, history)" :disabled="history.disabledSave">
                        <CopyOutlined v-if="item.key == 'copy'" />
                        <EditOutlined v-if="item.key == 'edit'" />
                        <ExportOutlined v-if="item.key == 'export'" />
                        <StarFilled v-if="
                          history.is_collect == 1 && item.key == 'collect'
                        " />
                        <StarOutlined v-if="
                          history.is_collect !== 1 && item.key == 'collect'
                        " />
                        {{
                          history.is_collect == 1 && item.key == "collect"
                            ? "已收藏"
                            : item.title
                        }}
                      </a-button>
                    </a-space>
                  </div>
                </a-card>
              </a-col>
              <a-col style="width: 100%; text-align: right; padding-right: 20px">
                <a-pagination v-model:current="page" :pageSize="10" :total="total" />
              </a-col>
            </a-row>
          </a-spin>
          <a-empty v-if="!historyList.length" style="
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              color: #999;
            " />
        </div>
        <div v-if="activeKey == 2" style="height: calc(100% - 104px);border: 1px solid #cccccc;border-top:none;">
          <scene-editor v-model:content="editorContent" v-model:title="editorTitle" placeholder="在左侧指令区输入相关信息"
            :show-title="true" editorBgColor="#f5f5f5" ref="sceneEditorRef" />
          <div class="bttom-area">
            <a-button type="primary" shape="round" style="margin-top: 10px;" @click="showAritleDrawer">发布到平台</a-button>
          </div>
        </div>
        <div class="chat-wrap" style="display: none;" v-if="chatCoreVisible && activeKey == 2">
          <ChatCore :TextMaxWith="800" :showUserMessage="false" :showRecommendList="false" :showInput="false"
            :visible="chatCoreVisible" :chatId="currentChatID" :userAutoMsg="userAutoMsg"
            @eventSourceFinish="eventSourceFinish" @stream="eventSourceStream" @eventSourceError="eventSourceError" />
          <MarkdownViewer ref="markdownViewerRef" />
        </div>
      </div>
    </div>

    <LoginModal :visible="loginVisible" @onClose="loginVisible = false" @loginCallback="loginCallback" />

    <a-modal :visible="materialModalVisible" title="选择推荐素材" centered @cancel="() => (materialModalVisible = false)"
      :footer="null" :width="1000" :body-style="{
        padding: '16px',
        minHeight: '500px',
      }">
      <div v-if="materialListSpinning" style="
          width: 100%;
          height: 468px;
          display: flex;
          justify-content: center;
          align-items: center;
        ">
        <a-spin tip="加载中..." />
      </div>
      <template v-else>
        <div class="material-cate-wrap" v-if="materialCates.length > 0">
          <div class="material-cate-part" v-for="(group, groupIndex) of materialCates" :key="groupIndex">
            <div class="material-cate-part-title">
              {{ group.group_name }}
            </div>
            <div class="material-cate-part-items" v-if="group.tags && group.tags.length > 0">
              <div v-for="(tag, tagIndex) of group.tags" :key="tagIndex" class="material-cate-part-item"
                :class="tag.checked ? 'material-cate-part-item-current' : ''" @click="onTagClick(tag, groupIndex)">
                {{ tag.tag_name }}
              </div>
            </div>
          </div>
        </div>
        <div class="material-tag-list-wrap beauty-scroller-bar">
          <div class="material-tag-list" v-if="currentMaterials.length > 0">
            <a-tag v-for="(material, materialIndex) of currentMaterials" :key="materialIndex" class="material-tag-item"
              @click.prevent="useMaterial(material)">
              <div>{{ material.material_content }}</div>
            </a-tag>
          </div>
          <div v-if="noMaterialList" style="
              width: 100%;
              height: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
            ">
            <a-empty description="暂无推荐素材" />
          </div>
        </div>
      </template>
    </a-modal>

    <member-ship-modal :visible="memberShipVisible" @close="closeMemberShip" />
    <ArticlePublish :visible="articleVisible" :title="editorTitle" :content="editorContent"
      :parentDom="$refs.contentPart" @onClose="closeArticlePublish"></ArticlePublish>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  ref,
  nextTick,
} from "vue";
import memberShipModal from "../../views/vip/modules/memberShip.vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Form, Modal, notification, message } from "ant-design-vue";
import ArticlePublish from "../../components/ArticlePublish/index.vue";
import {
  ThunderboltOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  StarOutlined,
  CopyOutlined,
  EditOutlined,
  ExportOutlined,
  StarFilled,
  ExclamationCircleOutlined
} from "@ant-design/icons-vue";
import SceneEditor from '../../components/SceneEditor/index.vue'
import MarkdownViewer from "../../components/MarkdownViewer/index.vue";
import ChatCore from "../../components/ChatCore/index.vue";
const useForm = Form.useForm;
export default defineComponent({
  name: "Scene",
  components: {
    ThunderboltOutlined,
    ChatCore,
    PlusOutlined,
    ClockCircleOutlined,
    StarOutlined,
    CopyOutlined,
    ExportOutlined,
    EditOutlined,
    StarFilled,
    ExclamationCircleOutlined,
    SceneEditor,
    MarkdownViewer,
    memberShipModal,
    ArticlePublish
  },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      editorTitle: '',
      detail: {},
      cateList: [],
      cateId: 0,
      currentCate: {},
      currentApp: {},

      currentChatID: "",
      userAutoMsg: "",
      chatCoreVisible: false,
      submitDisabled: false,

      loginVisible: false,
      activeKey: 2,
      tabList: [
        {
          title: "新创作的",
          key: 2,
        },
        {
          title: "已收藏的",
          key: 1,
        },
        {
          title: "历史记录",
          key: 0,
        },
      ],

      textareaValue:
        "介绍：你想看比明星八卦更劲爆的故事吗？这里有许多有趣的人物故事等你来发现！跟着我们去追寻人物身后的神秘面纱吧，一起来喝口茶，畅想世间奇闻趣事。",
      historyList: [],
      historySpinning: false,
      page: 1,
      total: 10,

      disclaimer_url: "", //免责声明
      noMaterialList: false,
      currentMaterialTagIds: [], //当前选中的标签Id（可多选）
      currentMaterials: [],

      materialModalVisible: false,
      materialListSpinning: false,
      currentFormItemIndex: 0,
      materialCates: [], //标签&标签组分类

      memberShipVisible: false,
      articleVisible: false
    });

    const sceneEditorRef = ref(null);

    const getCateDetail = () => {
      request
        .get("/work_ai", "/application/category/app_list", {
          cat_id: state.cateId,
        })
        .then((res) => {
          state.activeKey = 2;
          if (res.category) {
            state.detail = res.category;
          }
          if (res.list) {
            state.cateList = res.list;
            if (res.list.length > 0) {
              state.currentCate = res.list[0];
              if (
                state.currentCate.app_list &&
                state.currentCate.app_list.length > 0
              ) {
                state.currentApp = state.currentCate.app_list[0];
                refreshFormAndRules();
              }
            }

            // 根据appid匹配对应的app
            if (res.app_list && res.app_list.length > 0 && route.query.appId) {
              state.currentApp = res.app_list.find(
                (item) => item.id == route.query.appId
              );
            }
          }
        });
    };

    const onAppClick = (item) => {
      if (item.id == state.currentApp.id) {
        return;
      }
      state.currentChatID = null;
      state.userAutoMsg = "";
      state.chatCoreVisible = false;
      state.currentApp = item;
      refreshFormAndRules();
      state.historyList = [];
      state.activeKey = 2;
    };

    const rulesRef = ref({});

    const formRef = ref({});

    let validateKeywords = async (rule, value, item) => {
      console.log(rule, value, item);
      console.log(formRef.value);
      if (
        item.isRequired &&
        (!formRef.value[rule.field] || formRef.value[rule.field].length == 0)
      ) {
        return Promise.reject("请添加" + item.label);
      } else {
        return Promise.resolve();
      }
    };

    let { resetFields, validate, validateInfos } = useForm(formRef, rulesRef);

    const refreshFormAndRules = () => {
      formRef.value = {};
      rulesRef.value = {};
      nextTick(() => {
        if (state.currentApp && state.currentApp.user_form) {
          state.currentApp.user_form.forEach((item, index) => {
            if (item.formType == "multiSelect") {
              formRef.value["value" + index] = [];
            } else {
              formRef.value["value" + index] = null;
            }

            // 有默认值
            if (item.defaultValue) {
              if (item.formType == "keywords") {
                formRef.value["value" + index] = item.defaultValue;
              } else {
                item.placeholder = "示例:" + item.defaultValue;
              }
            }

            if (item.formType == "select") {
              rulesRef.value["value" + index] = [
                {
                  required: item.isRequired,
                  message: "请选择" + item.label,
                  trigger: "blur",
                },
              ];
            }
            if (item.formType == "keywords" || item.formType == "multiSelect") {
              rulesRef.value["value" + index] = [
                {
                  required: item.isRequired,
                  trigger: "blur",
                  validator: (rule, value) =>
                    validateKeywords(rule, value, item),
                },
              ];
            } else {
              rulesRef.value["value" + index] = [
                {
                  required: item.isRequired,
                  message: "请输入" + item.label,
                  trigger: "blur",
                },
              ];
            }
          });
        }
        validateInfos = useForm(formRef, rulesRef).validateInfos;
      });
    };

    const replaceFormText = (text) => {
      state.currentApp.user_form.forEach((item, index) => {
        if (formRef.value["value" + index]) {
          let key = `{${item.label}}`;
          text = text.split(key).join(formRef.value["value" + index]);
        } else {
          let key = `{${item.label}}`;
          text = text.split(key).join("");
        }
      });
      return text;
    };

    const onSubmit = () => {
      utils.checkLogin().then((isLogin) => {
        if (!isLogin) {
          state.loginVisible = true;
          return;
        }

        // 如果有默认值且用户未填写，则自动填入默认值
        if (state.currentApp && state.currentApp.user_form) {
          state.currentApp.user_form.forEach((item, index) => {
            // 有默认值
            if (
              item.defaultValue &&
              (!formRef.value["value" + index] ||
                formRef.value["value" + index].length == 0)
            ) {
              formRef.value["value" + index] = item.defaultValue;
              console.log(formRef.value["value" + index]);
            }
          });
        }

        nextTick(() => {
          validate().then(() => {
            state.chatCoreVisible = false;
            let params = {
              title: state.currentApp.name,
              user_form: formRef.value,
              application_id: state.currentApp.id,
              team_id: utils.getCurrentTeam() || 0,
            };
            request
              .post("/work_ai", "/chat/add", {
                ...params,
              })
              .then((res) => {
                if (res.chat_id) {
                  state.currentChatID = res.chat_id;
                  state.userAutoMsg = res.auto_msg;
                  state.chatCoreVisible = true;
                  state.submitDisabled = true;

                  editorContent.value = ''
                  editorStreamContent.value = ''
                }
              });
          });
        });
      });
    };

    const eventSourceFinish = (aiTxt) => {
      state.submitDisabled = false;
      let question = [];
      if (state.userAutoMsg) {
        question = state.userAutoMsg.split("\n").map((item) => {
          if (item) {
            return {
              label: item.split("：")[0],
              value: item.split("：")[1],
            };
          }
        });
        if (question && aiTxt) {
          request
            .post("/work_ai", "/user/chatHistory/add", {
              chat_id: state.currentChatID,
              aiTxt,
              question,
            })
            .then(({ result }) => {
              historyID.value = result
            })
        }
      }

      if (sceneEditorRef.value) {
        sceneEditorRef.value.writeFinish()
      }
    };

    const newKeywordsInputRef = ref(null);

    const showAddKeywords = (item) => {
      item.newKeywordsAdding = true;
      nextTick(() => {
        newKeywordsInputRef.value[0].focus();
      });
    };

    const addKeywords = (e, item, index) => {
      if (item.newKeywords) {
        if (!formRef.value["value" + index]) {
          formRef.value["value" + index] = [];
        }
        formRef.value["value" + index].push(item.newKeywords);
        item.newKeywords = "";
        item.newKeywordsAdding = false;
      } else {
        item.newKeywordsAdding = false;
      }
    };

    const removeKeywords = (index, tagIndex) => {
      formRef.value["value" + index].splice(tagIndex, 1);
    };

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 获取历史记录和收藏
    const getChatHistoryList = (application_id, is_collect) => {
      state.historySpinning = true;
      request
        .get("/work_ai", "/user/chatHistory/list", {
          application_id,
          is_collect,
          page: state.page,
          pageSize: 10,
        })
        .then((res) => {
          state.historyList = res.list.map((item) => {
            return {
              ...item,
              is_input: false,
              operateList: [
                {
                  title: "复制",
                  key: "copy",
                },
                {
                  title: "编辑",
                  key: "edit",
                },
                {
                  title: "导出",
                  key: "export",
                },
                {
                  title: "收藏",
                  key: "collect",
                },
              ],
            };
          });
          state.historySpinning = false;
          state.total = res.total;
        });
    };

    watch(
      () => state.page,
      (val) => {
        getChatHistoryList(state.currentApp.id, state.activeKey);
      }
    );

    watch(
      () => state.activeKey,
      (val, oldView) => {
        if (val == 1 || val == 0) {
          utils.checkLogin().then((isLogin) => {
            if (!isLogin) {
              state.loginVisible = true;
              return;
            }

            state.page = 1;
            state.historyList = [];
            getChatHistoryList(state.currentApp.id, val);
          })
        }
      }
    );

    const btnClick = (item, history) => {
      if (item.key == "edit") {
        if (history.is_input) {
          history.is_input = false;
          item.title = "编辑";
          request
            .put("/work_ai", "/user/chatHistory/update", {
              id: history.id,
              ai: history.ai,
            })
            .then((res) => {
              getChatHistoryList(state.currentApp.id, state.activeKey);
            });
          return;
        }
        history.is_input = true;
        item.title = "保存";
      }
      if (item.key == "copy") {
        utils.copyText(history.ai);
      }
      if (item.key == "export") {
        utils.export2Word(history.ai, 'file');
      }
      if (item.key == "collect") {
        if (history.is_collect == 0) {
          request
            .post("/work_ai", "/user/chatHistory/favorite", { id: history.id })
            .then((res) => {
              message.success("收藏成功");
              getChatHistoryList(state.currentApp.id, state.activeKey);
            });
        } else {
          request
            .post("/work_ai", "/user/chatHistory/cancelFavorite", {
              id: history.id,
            })
            .then((res) => {
              message.success("取消收藏成功");
              getChatHistoryList(state.currentApp.id, state.activeKey);
            });
        }
      }
    };

    const aiTxtChange = (data) => {
      if (data.ai) {
        data.disabledSave = false;
      } else {
        data.disabledSave = true;
      }
    };

    const disclaimerClick = () => {
      if (state.disclaimer_url) {
        window.open(state.disclaimer_url, "_blank");
      } else {
        request.get("/work_ai", "/config").then((res) => {
          if (res.list) {
            state.disclaimer_url = res.list.disclaimer_url;
            window.open(state.disclaimer_url, "_blank");
          }
        });
      }
    };

    const showMaterialListPop = (formItem, formItemIndex) => {
      state.currentFormItemIndex = formItemIndex;
      state.materialModalVisible = true;

      // 如果设置了默认标签
      state.currentMaterialTagIds = [];
      if (formItem.defaultTags && formItem.defaultTags.length > 0) {
        formItem.defaultTags.forEach((item) => {
          state.currentMaterialTagIds.push(item.value);
        });
      }
      getMaterialCates(formItem);
    };

    const getMaterialCates = (formItem) => {
      state.noMaterialList = false;
      state.currentMaterials = [];
      state.materialCates = [];
      state.materialListSpinning = true;
      let params = {
        patternIds: formItem.patternIds,
      };
      request
        .post("/work_ai", "/application/patternTag/material/list", {
          ...params,
        })
        .then((res) => {
          if (res.list) {
            if (res.list.length > 0) {
              res.list.forEach((tagGroup) => {
                let totalTag = {
                  tag_name: "全部",
                  tag_id: -1,
                  materials: [],
                };
                if (tagGroup.tags && tagGroup.tags.length) {
                  tagGroup.tags.forEach((tag) => {
                    tag.group_id = tagGroup.group_id;
                    totalTag.materials = totalTag.materials.concat(
                      tag.materials
                    );
                    delete tag.materials;
                  });
                }
                tagGroup.tags.unshift(totalTag);
              });
              state.materialCates = res.list;
              console.log("state.materialCates", state.materialCates);

              // 如果设置了默认标签
              if (state.currentMaterialTagIds.length > 0) {
                getCurrentMaterials(formItem);
              } else {
                // 没有筛选标签，则取全部
                state.materialCates.forEach((tagGroup) => {
                  tagGroup.tags[0].checked = true;
                  state.currentMaterials = state.currentMaterials.concat(
                    tagGroup.tags[0].materials
                  );
                });
                //去重
                let obj = {};
                state.currentMaterials = state.currentMaterials.reduce(
                  function (item, next) {
                    obj[next.id]
                      ? ""
                      : (obj[next.id] = true && item.push(next));
                    return item;
                  },
                  []
                );
              }
            } else {
              state.noMaterialList = true;
            }
          }
          state.materialListSpinning = false;
        });
    };

    const getCurrentMaterials = (formItem) => {
      state.currentMaterials = [];
      state.noMaterialList = false;
      let params = {
        patternIds: formItem.patternIds,
      };
      if (state.currentMaterialTagIds.length > 0) {
        params.tagids = state.currentMaterialTagIds;

        // 给标签加选中效果
        state.materialCates.forEach((tagGroup) => {
          // 该标签组是否有选择的标签
          let groupHasCheckedTag = false;
          tagGroup.tags.forEach((tag) => {
            tag.checked = false;
            if (state.currentMaterialTagIds.includes(tag.tag_id)) {
              tag.checked = true;
              groupHasCheckedTag = true;
            }
          });
          // 若没有，则给全部加选中效果
          if (!groupHasCheckedTag) {
            tagGroup.tags[0].checked = true;
          }
        });
      }
      request
        .post("/work_ai", "/application/patternTag/material/list", {
          ...params,
        })
        .then((res) => {
          if (res.list) {
            if (res.list.length > 0) {
              if (
                res.list[0].tags &&
                res.list[0].tags.length > 0 &&
                res.list[0].tags[0].materials &&
                res.list[0].tags[0].materials.length > 0
              ) {
                state.currentMaterials = res.list[0].tags[0].materials;
              } else {
                state.noMaterialList = true;
              }
            } else {
              state.noMaterialList = true;
            }
          }
        });
    };

    const onTagClick = (currantTag, groupIndex) => {
      if (currantTag.checked) {
        return;
      }
      state.currentMaterials = [];
      state.currentMaterialTagIds = [];
      let index = state.currentFormItemIndex;
      let currentFormItem = state.currentApp.user_form[index];
      //相同标签组下只能选一个标签
      state.materialCates[groupIndex].tags.forEach((tag) => {
        tag.checked = false;
        if (tag.tag_id == currantTag.tag_id) {
          tag.checked = true;
        }
      });
      state.materialCates.forEach((tagGroup) => {
        tagGroup.tags.forEach((tag) => {
          if (tag.checked && tag.tag_id > 0) {
            state.currentMaterialTagIds.push(tag.tag_id);
          }
        });
      });
      // 如果设置了默认标签
      if (state.currentMaterialTagIds.length > 0) {
        getCurrentMaterials(currentFormItem);
      } else {
        // 没有筛选标签，则取全部
        state.materialCates.forEach((tagGroup) => {
          tagGroup.tags[0].checked = true;
          state.currentMaterials = state.currentMaterials.concat(
            tagGroup.tags[0].materials
          );
        });
        console.log("state.currentMaterials", state.currentMaterials);
        //去重
        let obj = {};
        state.currentMaterials = state.currentMaterials.reduce(function (
          item,
          next
        ) {
          obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
          return item;
        },
          []);
      }
    };

    const useMaterial = (material) => {
      if (state.currentFormItemIndex) {
        let index = state.currentFormItemIndex;
        let item = state.currentApp.user_form[index];
        if (formRef.value["value" + index]) {
          if (item.formType == "keywords") {
            formRef.value["value" + index].push(material.material_content);
          } else {
            formRef.value["value" + index] += material.material_content;
          }
        } else {
          if (item.formType == "keywords") {
            formRef.value["value" + index] = [material.material_content];
          } else {
            formRef.value["value" + index] = material.material_content;
          }
        }
        state.currentFormItemIndex = 0;
      }

      state.materialModalVisible = false;
    };

    const editorContent = ref('')
    const editorStreamContent = ref('')
    const markdownViewerRef = ref(null)
    const historyID = ref(null)

    const eventSourceStream = (text) => {
      editorStreamContent.value += text
      editorContent.value = markdownViewerRef.value.parseMarkdown(editorStreamContent.value)
    }

    const onStoreClick = () => {
      if (!editorContent.value.trim()) {
        message.warning('请输入内容')
        return
      }

      if (!historyID.value) {
        message.warning('请在左侧指令区输入相关信息')
        return
      }

      request.put('/work_ai', '/user/chatHistory/update', {
        id: historyID.value,
        ai: editorContent.value
      }).then(res => {
        message.success('保存成功')
      })
    }

    const init = () => {
      state.cateId = 0;
      state.cateList = [];
      state.currentChatID = null;
      state.currentCate = {};
      state.currentApp = {};
      state.userAutoMsg = "";
      state.chatCoreVisible = false
      historyID.value = null


      eventSourceFinish();
      let cateId = route.params.cateId;
      if (cateId) {
        state.cateId = cateId;
        getCateDetail();
      }
    };

    init();

    watch(
      () => route.params.cateId,
      (val) => {
        if (val) {
          init();
        }
      }
    );

    watch(
      () => route.query.appId,
      (val) => {
        if (val) {
          getCateDetail();
        }
      }
    );

    const eventSourceError = (msg) => {
      message.warning(msg)
      state.memberShipVisible = true;
    }

    const closeMemberShip = () => {
      state.memberShipVisible = false;
    }
    const closeArticlePublish = () => {
      state.articleVisible = false
    }
    const showAritleDrawer = () => {
      if (!state.editorTitle) {
        return message.warning('请填写文章标题')
      }

      let pureText = editorContent.value.replace(/(<([^>]+)>)/gi, '');
      if (!pureText) {
        message.warning('请输入文字')
        return
      }
      console.log(pureText);
      state.articleVisible = true
    }
    return {
      ...toRefs(state),
      onAppClick,
      formRef,
      validateInfos,
      resetFields,
      onSubmit,
      eventSourceFinish,
      showAddKeywords,
      addKeywords,
      removeKeywords,
      newKeywordsInputRef,
      loginCallback,
      btnClick,
      disclaimerClick,
      showMaterialListPop,
      useMaterial,
      onTagClick,
      aiTxtChange,
      editorContent,
      markdownViewerRef,
      eventSourceStream,
      onStoreClick,
      eventSourceError,
      closeMemberShip,
      closeArticlePublish,
      sceneEditorRef,
      showAritleDrawer,
    };
  },
});
</script>

<style lang="less" scoped>
.scene {
  width: 100%;
  height: 100%;
  // background-color: #f5f5f5;
  padding: 20px;

  .header {
    font-size: 18px;
    font-weight: bold;
    height: 28px;
    line-height: 28px;
  }

  .step-wrap {
    background-color: #fff;
    padding: 20px;
    border-radius: 6px;
    margin-top: 20px;
  }

  .content-card {
    position: relative;
    background-color: #fff;
    border-radius: 6px;
    // margin-top: 10px;
    display: flex;
    width: 100%;
    // height: calc(100% - 30px);
    height: 100%;

    .content-split-vertical {
      border-right: 1px solid #f5f5f5;
    }

    .content-part {
      height: 100%;
      position: relative;

      .content-part-title {
        padding: 10px 16px;
        font-weight: bold;
        border-bottom: 1px solid #f5f5f5;
      }

      .cate-list {
        overflow: hidden auto;
        height: calc(100% - 53px);
        padding: 10px 16px;

        .cate-card {
          margin-bottom: 10px;

          .cate-name {
            padding-bottom: 10px;
          }

          .app-card {
            background-color: #fff;
            border-radius: 12px;
            border: 2px solid #f1f1f1;
            padding: 10px 16px;
            margin-bottom: 10px;
            display: flex;
            cursor: pointer;

            .app-icon {
              width: 32px;
              height: 32px;
              border-radius: 4px;
              object-fit: cover;
              margin-right: 10px;
            }

            .app-icon-block {
              width: 32px;
              height: 32px;
              border-radius: 4px;
              margin-right: 10px;
              background-color: #f1f1f1;
            }

            .app-right {
              flex: 1;

              .app-name {
                font-weight: 600;
              }

              .app-info {
                color: #666;
                font-size: 12px;
                margin-top: 5px;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }
            }
          }

          .app-card-current {
            background-color: #f3f0ff;
            border-color: #5a54f9;
          }
        }
      }

      .form-list {
        overflow: hidden auto;
        height: calc(100% - 133px);
        padding: 10px 16px 0 16px;

        .keywords-wrap {
          min-height: 60px;
          border: 1px solid #d9d9d9;
          display: flex;
          flex-wrap: wrap;
          padding: 10px;

          .add-keyword-button {
            width: 60px;
            height: 24px;
            background-color: #fafafa;
            border: 1px dashed #ccc;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 6px;
            font-size: 12px;
          }
        }

        :deep(label) {
          width: 100%;
        }
      }

      .form-submit-wrap {
        width: 100%;
        height: 90px;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 20px 20px 20px;
        border-top: 1px solid #f5f5f5;
        border-radius: 0 0 6px 0;
        position: relative;

        .disclaimer-wrap {
          position: absolute;
          left: 24px;
          bottom: 8px;
          color: #999;
          font-size: 12px;
          cursor: pointer;

          &:hover {
            color: @primary-color;
          }
        }
      }

      :deep(.ant-tabs-bar) {
        margin: 0;
      }
    }
  }

  .history {
    width: 100%;
    height: 94%;
    overflow: hidden auto;

    .title {
      color: #00000073;
    }

    .textarea {
      margin-bottom: 10px;
    }

    .introduce {
      margin-top: 20px;
      margin-bottom: 15px;
    }

    .operate {
      border: 1px solid #f2f2f2;
      padding: 4px 20px;
      border-radius: 24px;
      color: #00000073;
      cursor: pointer;
    }
  }

  .chat-wrap {
    width: 100%;
    height: calc(100% - 46px);
    padding: 10px 20px;
  }
}

.material-cate-wrap {
  padding-right: 10px;

  .material-cate-part {
    display: flex;
    padding-bottom: 10px;
    font-size: 15px;

    .material-cate-part-title {
      font-weight: 600;
    }

    .material-cate-part-items {
      display: flex;
      padding-left: 10px;

      .material-cate-part-item {
        margin-left: 15px;
        cursor: pointer;
      }

      .material-cate-part-item-current {
        color: @primary-color;
      }
    }
  }
}

.material-tag-list-wrap {
  margin-top: 10px;
  width: 100%;
  height: 400px;
  overflow: hidden auto;

  .material-tag-list {
    width: 100%;
    padding-right: 10px;

    .material-tag-item {
      margin-bottom: 8px;
      margin-right: 0;
      cursor: pointer;
      font-size: 14px;
      padding: 8px 10px;
      display: block;
      border-radius: 6px;
      white-space: pre-wrap;
      word-break: break-all;
      transition: 0.2s cubic-bezier(0.4, 0.2, 1);

      &:hover {
        color: #531dab;
        background: #f9f0ff;
        border-color: #d3adf7;
      }
    }
  }
}

.bttom-area {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: flex-end;
  height: 60px;
  background-color: #fff;
  padding: 10px;
}
</style>
